const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    charset: 'utf8mb4'
};

async function testGemService() {
    let connection;

    try {
        console.log('🔮 测试宝石系统服务...');

        // 连接数据库
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功');

        // 1. 测试查询宝石基础数据
        console.log('\n1️⃣ 测试查询宝石基础数据');
        const [gemBases] = await connection.execute('SELECT * FROM gem_base LIMIT 5');
        console.log('📊 宝石基础数据:');
        gemBases.forEach(gem => {
            console.log(`  - ${gem.name} (类型:${gem.type}): ${gem.description}`);
        });

        // 2. 测试查询开矿配置
        console.log('\n2️⃣ 测试查询开矿配置');
        const [miningConfigs] = await connection.execute('SELECT * FROM gem_mining');
        console.log('⛏️ 开矿配置:');
        miningConfigs.forEach(config => {
            console.log(`  - ${config.name}: 需要${config.key_item_name}, 获得${config.min_level}-${config.max_level}级宝石`);
        });

        // 3. 测试为角色添加宝石
        console.log('\n3️⃣ 测试为角色添加宝石');
        const characterId = 2001; // 假设角色ID

        // 检查角色是否存在
        const [characters] = await connection.execute('SELECT id, name FROM characters WHERE id = ?', [characterId]);
        if (characters.length === 0) {
            console.log('❌ 角色不存在，跳过宝石添加测试');
        } else {
            console.log(`✅ 找到角色: ${characters[0].name}`);

            // 添加一个钻石宝石到角色背包
            const gemBaseId = 1; // 钻石
            const gemName = '钻石(8级)';
            const level = 8;
            const attributes = JSON.stringify({
                physical_resistance: 12,
                critical_rate: 12,
                speed: 12
            });

            try {
                await connection.execute(`
          INSERT INTO character_gem_inventory 
          (character_id, gem_base_id, name, level, attributes, num, status, obtained_at) 
          VALUES (?, ?, ?, ?, ?, 1, 1, NOW())
        `, [characterId, gemBaseId, gemName, level, attributes]);

                console.log('✅ 成功添加宝石到角色背包');

                // 查询角色宝石背包
                const [gems] = await connection.execute(`
          SELECT cgi.*, gb.name as gem_base_name, gb.type 
          FROM character_gem_inventory cgi 
          JOIN gem_base gb ON cgi.gem_base_id = gb.id 
          WHERE cgi.character_id = ?
        `, [characterId]);

                console.log('💎 角色宝石背包:');
                gems.forEach(gem => {
                    console.log(`  - ${gem.name} (${gem.gem_base_name}): 等级${gem.level}, 数量${gem.num}`);
                });

            } catch (error) {
                if (error.code === 'ER_DUP_ENTRY') {
                    console.log('ℹ️ 宝石已存在，跳过添加');
                } else {
                    throw error;
                }
            }
        }

        // 4. 测试宝石镶嵌
        console.log('\n4️⃣ 测试宝石镶嵌');
        const equipmentId = 1;
        const equipmentType = 'weapon';
        const socketSlot = 1;

        try {
            // 获取角色的第一个宝石
            const [gems] = await connection.execute(`
        SELECT * FROM character_gem_inventory 
        WHERE character_id = ? AND status = 1 
        LIMIT 1
      `, [characterId]);

            if (gems.length > 0) {
                const gem = gems[0];

                // 镶嵌宝石
                await connection.execute(`
          INSERT INTO equipment_gem_socket 
          (character_id, equipment_id, equipment_type, socket_slot, gem_inventory_id, gem_base_id, gem_name, gem_level, gem_attributes, socketed_at) 
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        `, [characterId, equipmentId, equipmentType, socketSlot, gem.id, gem.gem_base_id, gem.name, gem.level, gem.attributes]);

                console.log('✅ 成功镶嵌宝石到装备');

                // 更新宝石状态为已使用
                await connection.execute(`
          UPDATE character_gem_inventory 
          SET status = 0 
          WHERE id = ?
        `, [gem.id]);

                console.log('✅ 更新宝石状态为已使用');

                // 查询装备宝石信息
                const [sockets] = await connection.execute(`
          SELECT * FROM equipment_gem_socket 
          WHERE character_id = ? AND equipment_id = ? AND equipment_type = ?
        `, [characterId, equipmentId, equipmentType]);

                console.log('🔧 装备宝石镶嵌信息:');
                sockets.forEach(socket => {
                    console.log(`  - 槽位${socket.socket_slot}: ${socket.gem_name} (等级${socket.gem_level})`);
                });

            } else {
                console.log('❌ 没有可用的宝石进行镶嵌测试');
            }

        } catch (error) {
            if (error.code === 'ER_DUP_ENTRY') {
                console.log('ℹ️ 宝石已镶嵌，跳过镶嵌测试');
            } else {
                throw error;
            }
        }

        console.log('\n🎉 宝石系统服务测试完成！');

    } catch (error) {
        console.error('❌ 测试失败:', error);
        throw error;
    } finally {
        if (connection) {
            await connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

// 运行测试
testGemService().catch(console.error);
